//
//  ViewController.m
//  OCR
//
//  Created by 刘家俊 on 2021/5/6.
//

#import "ViewController.h"
//#import <opencv2/opencv.hpp>
//#import <opencv2/imgproc/types_c.h>
//#import <opencv2/imgcodecs/ios.h>
#import <TesseractOCR/TesseractOCR.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self tesseractRecognizeImage:[UIImage imageNamed:@"WechatIMG74.jpeg"]];
}

////扫描身份证图片，并进行预处理，定位号码区域图片并返回
//- (UIImage *)opencvScanCard:(UIImage *)image {
//
//    //将UIImage转换成Mat
//    cv::Mat resultImage;
//    UIImageToMat(image, resultImage);
//    //转为灰度图
//    cvtColor(resultImage, resultImage, cv::COLOR_BGR2GRAY);
//    //利用阈值二值化
//    cv::threshold(resultImage, resultImage, 100, 255, CV_THRESH_BINARY);
//    //腐蚀，填充（腐蚀是让黑色点变大）
//    cv::Mat erodeElement = getStructuringElement(cv::MORPH_RECT, cv::Size(26,26));
//    cv::erode(resultImage, resultImage, erodeElement);
//    //轮廊检测
//    std::vector<std::vector<cv::Point>> contours;//定义一个容器来存储所有检测到的轮廊
//    cv::findContours(resultImage, contours, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cvPoint(0, 0));
//    //取出身份证号码区域
//    /*
//     std::vector<cv::Rect> rects;
//     cv::Rect numberRect = cv::Rect(0,0,0,0);
//     std::vector<std::vector<cv::Point>>::const_iterator itContours = contours.begin();
//     for ( ; itContours != contours.end(); ++itContours) {
//     cv::Rect rect = cv::boundingRect(*itContours);
//     rects.push_back(rect);
//     //算法原理
//     if (rect.width > numberRect.width && rect.width > rect.height * 5) {
//     numberRect = rect;
//     }
//     }
//     //身份证号码定位失败
//     if (numberRect.width == 0 || numberRect.height == 0) {
//     return nil;
//     }
//     */
//    //不只取身份证 而是取整个照片区域
//    cv::Rect numberRect = cv::Rect(0,0,image.size.width,image.size.height);
//
//    //定位成功成功，去原图截取身份证号码区域，并转换成灰度图、进行二值化处理
//    cv::Mat matImage;
//    UIImageToMat(image, matImage);
//    resultImage = matImage(numberRect);
//    cvtColor(resultImage, resultImage, cv::COLOR_BGR2GRAY);
//    cv::threshold(resultImage, resultImage, 80, 255, CV_THRESH_BINARY);
//    //将Mat转换成UIImage
//    UIImage *numberImage = MatToUIImage(resultImage);
//    return numberImage;
//}

//利用TesseractOCR识别文字
- (void)tesseractRecognizeImage:(UIImage *)image {
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        G8Tesseract *tesseract = [[G8Tesseract alloc] initWithLanguage:@"eng+chi_sim"];
            //模式
        tesseract.engineMode = G8OCREngineModeTesseractOnly;
        tesseract.maximumRecognitionTime = 60;
        tesseract.pageSegmentationMode = G8PageSegmentationModeAutoOnly;
        //灰化 如果是英文或者数字推荐使用。如果是汉字不推荐使用
//        tesseract.image = [image g8_blackAndWhite];
        tesseract.image = image;
        [tesseract recognize];
        
        NSLog(@"识别出的文字是 - \n%@", tesseract.recognizedText);
    });
}


@end
